package top.callname.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;






import top.callname.bean.ClassBean;
import top.callname.bean.ConstanstBean;
import top.callname.bean.RspInfoBean;
import top.callname.bean.SignBean;
import top.callname.bean.SignPageList;
import top.callname.bean.SignRecordBean;
import top.callname.bean.SignRecordPageList;
import top.callname.bean.StudentBean;
import top.callname.bean.StudentPageList;
import top.callname.dao.ClassDao;
import top.callname.dao.SignDao;
import top.callname.dao.SignRecordDao;
import top.callname.dao.StudentDao;
import top.callname.service.SignService;
import top.callname.util.DateUtil;

public class SignServiceImpl implements SignService{

	private SignDao signDao = new SignDao();
	private SignRecordDao signRecordDao = new SignRecordDao();
	private StudentDao studentDao = new StudentDao();
	private ClassDao classDao = new ClassDao();
	private Logger logger = Logger.getLogger(SignServiceImpl.class);
	
	@Override
	public SignPageList getListPageByPid(int page, Integer pid) {
		SignPageList pageList = signDao.selectPageByPid(page, pid);
		for (int i = 0; i < pageList.getList().size(); i++) {
			SignBean bean = pageList.getList().get(i);
			String classNames = getClassNamesByCids(bean.getCids());
			pageList.getList().get(i).setClassNames(classNames);
		}
		return pageList;
	}

	@Override
	public RspInfoBean signIng(String openid, String randNo) {
		/**
		 * 签到流程
		 * 1.根据openid查询是否绑定系统
		 * 2.根据randNo查询系统是否存在签到记录
		 * 3.记录签到信息
		 * 4.返回编码
		 */
		RspInfoBean rsp = new RspInfoBean();
		try {
			Integer.valueOf(randNo);
			//查询该用户是否存在系统中
			StudentBean bean = studentDao.selectByOpenid(openid);
			if(bean != null){
				//查询有效的签到任务
				SignBean sign = signDao.selectByRandNo(randNo);
				if(sign != null){
					//判断是否重复签到
					SignRecordBean record = signRecordDao.selectByStuNoAndSignId(bean.getStuNo(),sign.getSignId());
					if(record == null){
						SignRecordBean signRecord = new SignRecordBean();
						signRecord.setSignId(sign.getSignId());
						signRecord.setStuNo(bean.getStuNo());
						//记录签到表
						if(signRecordDao.addSignRecord(signRecord)){
							rsp.setRspCode(ConstanstBean.RSP_SUCCESS);
							rsp.setRspDesc("签到成功：时间【"+DateUtil.dateToStrLong(new Date())+"】！");
						}else{
							rsp.setRspDesc("签到失败！");
						}
					}else{
						rsp.setRspDesc("签到失败：您已签到，请不要重复操作！");
					}
					
				}else{
					rsp.setRspDesc("签到失败：签到时间已过或校验码有误！");
				}
				
			}else{
				rsp.setRspDesc("该用户不存在系统中，请先注册！");
			}
		} catch (Exception e) {
			//转换出错说明发送的编码有误
			rsp.setRspDesc("签到失败：校验码有误，只能为数字！");
		} 
		return rsp;
	}

	@Override
	public SignBean getInuseSignByPid(Integer pid) {
		SignBean bean = signDao.selectByPid(pid);
		//查询班级
		if(bean!=null){
			bean.setClassNames(getClassNamesByCids(bean.getCids()));
			bean.setRspCode(ConstanstBean.RSP_SUCCESS);
			return bean;
		}else{
			//无数据
			bean = new SignBean();
			bean.setRspCode(ConstanstBean.RSP_FAULT);
		}
		return bean;
	}

	@Override
	public RspInfoBean stopSignTask(Integer signId,Integer pid) {
			boolean f = signDao.updateStatusBySignId(signId, pid);
			RspInfoBean rsp = new RspInfoBean();
			if(f){
				rsp.setRspCode(ConstanstBean.RSP_SUCCESS);
				rsp.setRspDesc("签到任务终止成功！");
			}else{
				rsp.setRspCode(ConstanstBean.RSP_FAULT);
				rsp.setRspDesc("签到任务终止失败！");
			}
			return rsp;
	}

	@Override
	public RspInfoBean addSignTask(SignBean signBean) {
		RspInfoBean rsp = new RspInfoBean();
		boolean f = signDao.addSign(signBean);
		if(f){
			rsp.setRspCode(ConstanstBean.RSP_SUCCESS);
			rsp.setRspDesc("签到任务创建成功！");
		}else{
			rsp.setRspCode(ConstanstBean.RSP_FAULT);
			rsp.setRspDesc("签到任务创建失败！");
		}
		return rsp;
	}

	@Override
	public SignBean getSignTaskInfo(Integer signId) {
		SignBean bean = signDao.selectBySignId(signId);
		if(bean!=null){
			bean.setClassNames(getClassNamesByCids(bean.getCids()));
			bean.setSignTotal(signDao.getCount("t_student", "where cid in( "+bean.getCids()+" )"));
			bean.setSignCount(signDao.getCount("t_sign_record", "where sign_id="+signId));
			bean.setRspCode(ConstanstBean.RSP_SUCCESS);
		}else{
			bean = new SignBean();
			bean.setRspCode(ConstanstBean.RSP_FAULT);
			bean.setRspDesc("签到任务查询失败！");
		}
		return bean;
	}
	
	
	private String getClassNamesByCids(String cids){
		List<ClassBean> students = classDao.selectByCids(cids);
		String classNames = "";
		for (int i = 0; i < students.size(); i++) {
			if(i==students.size()-1){
				classNames += students.get(i).getClassName();
			}else{
				classNames += students.get(i).getClassName()+"，";
			}
		}
		return classNames;
	}

	@Override
	public SignRecordPageList getYesSignListBySignId(int page, Integer signId) {
		return signRecordDao.selectSignListBySignId(page, signId);
	}

	@Override
	public StudentPageList getNoSignListBySignId(int page, Integer signId) {
		SignBean bean = signDao.selectBySignId(signId);
		return signRecordDao.selectNoSignList(page, bean);
	}

	@Override
	public void exportSignRecord(HttpServletRequest request, HttpServletResponse response, Integer signId) {
		SignBean bean = signDao.selectBySignId(signId);
		ArrayList<SignRecordBean> signList = signRecordDao.selectSignListBySignId(signId);
		ArrayList<StudentBean> studentList = signRecordDao.selectNoSignList(bean);
		HSSFWorkbook wb = new HSSFWorkbook();
		  //创建table工作薄
		HSSFSheet sheet1 = wb.createSheet("已签到用户");
		HSSFSheet sheet2 = wb.createSheet("未签到用户");
		
		HSSFRow row;
		HSSFCell cell;
		logger.info("导出数据：查询到已签到记录 "+signList.size()+" 条");
		logger.info("导出数据：查询到未签到记录 "+studentList.size()+" 条");
		//创建表头
    	//根据表格行创建单元格
		row = sheet1.createRow(0);
    	cell = row.createCell(0);
        cell.setCellValue("编号");
        cell = row.createCell(1);
        cell.setCellValue("学号");
        cell = row.createCell(2);
        cell.setCellValue("姓名");
        cell = row.createCell(3);
        cell.setCellValue("签到时间");
        cell = row.createCell(4);
        cell.setCellValue("所在班级");
        
		for(int i = 0; i < signList.size(); i++) {
			row = sheet1.createRow(i+1);
	    	//创建数据
	    	SignRecordBean obj = signList.get(i);
	    	cell = row.createCell(0);
	        cell.setCellValue(obj.getRid());
	        cell = row.createCell(1);
	        cell.setCellValue(obj.getStuNo());
	        cell = row.createCell(2);
	        cell.setCellValue(obj.getStuName());
	        cell = row.createCell(3);
	        cell.setCellValue(obj.getSignTime());
	        cell = row.createCell(4);
	        cell.setCellValue(obj.getClassName());
		}
		
		//创建未签到的用户
		//根据表格行创建单元格
		row = sheet2.createRow(0);
    	cell = row.createCell(0);
        cell.setCellValue("学号");
        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellValue("签到时间");
        cell = row.createCell(3);
        cell.setCellValue("所在班级");
        
        for(int i = 0; i < studentList.size(); i++) {
			row = sheet2.createRow(i+1);
	    	//创建数据
			StudentBean obj = studentList.get(i);
	    	cell = row.createCell(0);
	        cell.setCellValue(obj.getStuNo());
	        
	        cell = row.createCell(1);
	        cell.setCellValue(obj.getStuName());
	       
	        cell = row.createCell(2);
	        cell.setCellValue("--");
	        
	        cell = row.createCell(3);
	        cell.setCellValue(obj.getClassName());
		}
        try {
	        //下载文件
	    	String userAgent = request.getHeader("User-Agent");
	        //针对IE或者以IE为内核的浏览器：
	    	String fileName = bean.getDesc()+".xls";
	        if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
	            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
	        } else {
	        	//非IE浏览器的处理：
	            fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
	        }
	        //设置content-disposition响应头控制浏览器以下载的方式打开文件
	        response.setHeader("content-disposition","attachment;filename="+fileName);
	        //通过response对象获取OutputStream输出流对象
	        wb.write(response.getOutputStream());
		
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				wb.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public RspInfoBean signIngByAdmin(String stuNo, Integer signId) {
		RspInfoBean rsp = new RspInfoBean();
		SignRecordBean signRecord = new SignRecordBean();
		signRecord.setSignId(signId);
		signRecord.setStuNo(stuNo);
		if(signRecordDao.addSignRecord(signRecord)){
			rsp.setRspCode(ConstanstBean.RSP_SUCCESS);
			rsp.setRspDesc("管理员手动签到成功：时间【"+DateUtil.dateToStrLong(new Date())+"】！");
		}else{
			rsp.setRspCode(ConstanstBean.RSP_FAULT);
			rsp.setRspDesc("管理员手动签到失败！");
		}
		return rsp;
	}

	@Override
	public RspInfoBean removeSignRecord(Integer rid) {
		RspInfoBean rsp = new RspInfoBean();
		if(signRecordDao.deleteByPrimaryKey(rid)){
			rsp.setRspCode(ConstanstBean.RSP_SUCCESS);
			rsp.setRspDesc("删除签到记录成功！");
		}else{
			rsp.setRspCode(ConstanstBean.RSP_FAULT);
			rsp.setRspDesc("删除签到记录失败！");
		}
		return rsp;
	}
	

}
